$(function(){
	initframe();
	connection();
});
var websocket;
var concurrentRoom;
 
function connection(){
    //首先判断是否 支持 WebSocket
  //   if('WebSocket' in window) {
  //       websocket = new WebSocket("ws://localhost:8080/filesharingsystem/websocket");
  //   } else if('MozWebSocket' in window) {
  //       websocket = new MozWebSocket("ws://localhost:8080/filesharingsystem/websocket");
		// }
    // } else {
    //     websocket = new SockJS("http://localhost:8080/filesharingsystem/sockjs/websocket");
   // }
	websocket = new SockJS(getRootPath_web()+"websocket");

    // 打开时
    websocket.onopen = function(evnt) {
        console.log("  websocket.onopen  ");
    };


    // 处理消息时
    websocket.onmessage = function(evnt) {
		
		var msg = JSON.parse(evnt.data);
		switch(msg.pid){
			case '1':
				var text = $('#displayBox').textbox('getText');
				text += msg.source+' ';
				text += msg.timeStamp + '\n';
				text += msg.msgContent + '\n';
				$('#displayBox').textbox('setText',text);
				var scrollTop = $("#_easyui_textbox_input1")[0].scrollHeight;
				$("#_easyui_textbox_input1").scrollTop(scrollTop);
				break;
			case '0':
				var div = '<div class="menu-item" onclick="javascript:joinRoom(this);" room="'+msg.msgContent+'"><div class="menu-text" style="height: 30px; line-height: 30px;">'+msg.msgContent+'</div></div>'
				$("#room").append(div);
				break;
			case '2':
				$.messager.alert('错误', msg.msgContent,'error');
				break;
		}
		
		
		
		
        console.log("  websocket.onmessage   ");
    };


    websocket.onerror = function(evnt) {
        console.log("  websocket.onerror  ");
    };

    websocket.onclose = function(evnt) {
        console.log("  websocket.onclose  ");
    };


    // 点击了发送消息按钮的响应事件
	$('#sendBtn').bind('click', function(){
		// 获取消息内容
		var text = $('#inputBox').textbox('getText');
		$('#inputBox').textbox('clear');
		// 判断
		if(text == null || text == "" || concurrentRoom == null || concurrentRoom == ""){
		    alert(" content  can not empty!! or concurrentRoom unchoose");
		    return false;
		}
		
		var msg = {
			pid:"1",
		    msgContent: text
		};
		
		// 发送消息
		websocket.send(JSON.stringify(msg));
    });
}

function initframe(){
	$('#chatFrame').dialog({
	    width:440,
	    height:362,
		split:false,
	    title:'群聊',
		content:[$('#displayBox'),$('#roomlist'),$('#inputBox'),$('#sendBtn')],
		closable:true,
		closed:true
	});
	$('#displayBox').textbox({
		width:$('#chatFrame').width()-10,
		height:128,
		multiline:true,
		editable:false
	});
	$('#inputBox').textbox({
		width:$('#chatFrame').width()-10,
		height:108,
		multiline:true,
	});
	$(".textbox").css('margin','5px');
	$('#sendBtn').linkbutton({
		iconCls: 'icon-ok'
	});
	$('#roomlist').splitbutton({
		iconCls: 'icon-add',
		menu: '#room'
	});
	$("#roomlist").click(function(){
		$('#createRoomDialog').dialog("open"); 
	});
	
	$('#createRoomDialog').dialog({
		title: '新建群组',
		width: 188,
		height: 90,
		closed: false,
		cache: false,
		modal: true,
		closed: true
	});
	 $('#roomName').textbox({
        prompt:'新建群组名',
        buttonIcon:'icon-ok',
        iconAlign:'left',
		onClickButton:function(){
			
							// 获取消息内容
							var text = $('#roomName').textbox('getText');
							$('#roomName').textbox('clear');
							// 判断
							if(text == null || text == ""){
							    alert(" content  can not empty!!");
							    return false;
							}		
							createRoom(text);
							$('#createRoomDialog').dialog("close");
						}
	});
	$("#createRoomDialog span[class=textbox]").css({'margin':'10px'});
}

function joinRoom(room){	

	if(room!=null && room != ""){
		var msg = {
			pid: "0",
			msgContent: $(room).attr("room")
		};
		concurrentRoom = $(room).attr("room");
		$("#chatFrame").dialog('setTitle',"房间:"+$(room).attr("room"));
		// 发送消息
		websocket.send(JSON.stringify(msg));
	}
}
function createRoom(text){	
	if(text!=null && text != ""){
		var msg = {
			pid: "0",
			msgContent: text
		};
		concurrentRoom = text;
		$("#chatFrame").dialog('setTitle',"房间:"+text);
		// 发送消息
		websocket.send(JSON.stringify(msg));
	}
}
function openChat(){
	$('#chatFrame').dialog("open");
}
function getRootPath_web() {
						//获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
	var curWwwPath = window.document.location.href;
						            //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
	var pathName = window.document.location.pathname;
	var pos = curWwwPath.indexOf(pathName);
						            //获取主机地址，如： http://localhost:8083
	var localhostPaht = curWwwPath.substring(0, pos);
	var projectName = pathName.substring(0, pathName.substr(1).indexOf('/')+2);
	return (localhostPaht + projectName);
}